package cn.learn.designpattern.observer;

import java.util.ArrayList;

/**
 * 天气
 *
 * @author huangyezhan
 * @date 2018/11/26-0:02
 */
public class WeatherData implements Subject {
    /**
     * 存放注册观察者对象的数组
     */
    private final ArrayList<Observer> observers;

    /*
     * 主题变化的几个状态,变化通知观察者
     */
    /**
     * 温度
     */
    private float temperature;
    /**
     * 湿度
     */
    private float humidity;
    /**
     * 气压
     */
    private float pressure;

    public WeatherData() {
        observers = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void removedObserver(Observer o) {
        int i = observers.indexOf(o);
        if (i >= 0) {
            observers.remove(i);
        }
    }

    @Override
    public void notifyObservers() {
        for (int i = 0; i < observers.size(); i++) {
            Observer observer = observers.get(i);
            observer.update(temperature, humidity, pressure);
        }
    }


    public void meassSurementsChanged() {
        this.notifyObservers();
    }

    public void setMeassSurements(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        meassSurementsChanged();
    }

}

/**
 * 具体观察者
 *
 * @author huangyezhan
 * @date 2018/11/26-0:31
 */
class CurrentConditionsDisplay implements Observer {
    /**
     * 温度
     */
    private float temperature;
    /**
     * 湿度
     */
    private float humidity;

    /**
     * 保留着 Subject的对象, 只是为了以后方便删除注册
     */
    private Subject weatherData;

    public CurrentConditionsDisplay(Subject weatherData) {
        this.weatherData = weatherData;
        weatherData.registerObserver(this);
    }

    @Override
    public void update(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        display();
    }

    public void display() {
        System.out.println("temperature（温度）==>" + temperature + "\r\nhumidity（湿度）==>" + humidity);
    }

}

/**
 * 测试类
 */
class TestObserver{

    public static void main(String[] args) {
        // 定义一个天气监控台
        WeatherData weatherData = new WeatherData();
        // 定义一个当前天气展示面板
        CurrentConditionsDisplay display = new CurrentConditionsDisplay(weatherData);

        // 定义天气监控台检测天气变化
        weatherData.setMeassSurements(36.7F,70.2F, 50.0F);
    }

}
